package com.maddox.relax.nfc

import android.app.PendingIntent
import android.content.Intent
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.maddox.relax.R
import com.maddox.relax.databinding.ActivityNfcWriteBinding
import com.maddox.relax.util.AppUtils
import com.maddox.relax.util.LogUtil
import java.util.*

/**
 * Nfc 写入页面
 */
class NfcWriteActivity : AppCompatActivity() {

    lateinit var nfcAdapter: NfcAdapter
    lateinit var pendingIntent: PendingIntent
    lateinit var bd:ActivityNfcWriteBinding

    //是否启用加密校验
    var isEncrypt = false
    //是否开启写入功能
    var writeOpen = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd = DataBindingUtil.setContentView(this,R.layout.activity_nfc_write)
        initView()

    }

    private fun initView() {
        bd.header.toolbarTitle.text = "写入信息"
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (nfcAdapter == null) {
            Toast.makeText(this, "当前设备不支持NFC", Toast.LENGTH_SHORT).show()
            return
        }
        pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, this::class.java), 0)

        bd.toggleWrite.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) writeOpen =true else writeOpen=false
        }
        bd.toggleEncrypt.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) isEncrypt =true else isEncrypt=false
        }

    }

    override fun onResume() {
        super.onResume()
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null)
    }

    override fun onPause() {
        super.onPause()
        nfcAdapter.disableForegroundDispatch(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (!writeOpen) return
        val writeContent = bd.inputContent.text.toString().trim()
        if (TextUtils.isEmpty(writeContent)) {
            Toast.makeText(this, "请输入要写入的内容", Toast.LENGTH_SHORT).show()
            return
        }
        val tag: Tag? = intent?.getParcelableExtra(NfcAdapter.EXTRA_TAG)
        if (tag == null) return
        val ndefRecords = createNdefRecords(tag, writeContent)
        val ndefMessage = NdefMessage(ndefRecords)
        val size = ndefMessage.byteArrayLength

        try {
            val ndef = Ndef.get(tag)
            if (ndef != null) {
                ndef.connect()
                if (!ndef.isWritable) {
                    Toast.makeText(this, "当前为只读标签,无法写入", Toast.LENGTH_SHORT).show()
                    return
                }
                if (ndef.maxSize < size) {
                    Toast.makeText(this, "标签空间不足,无法写入", Toast.LENGTH_SHORT).show()
                    return
                }
                ndef.writeNdefMessage(ndefMessage)
                Toast.makeText(this, "写入标签成功", Toast.LENGTH_SHORT).show()
            } else {
                val ndefFormat = NdefFormatable.get(tag)
                if (ndefFormat != null) {
                    ndefFormat.connect()
                    ndefFormat.format(ndefMessage)
                    Toast.makeText(this, "写入标签成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "标签不支持Ndef数据,无法写入", Toast.LENGTH_SHORT).show()
                }
            }
        } catch (e: Exception) {
            LogUtil.d("写入标签异常:${e.message}")
            Toast.makeText(this, "写入标签异常,请检查", Toast.LENGTH_SHORT).show()
        }


    }

    private fun createNdefRecords(tag: Tag, writeContent: String): Array<NdefRecord> {
        var tmpContent = writeContent
        if (isEncrypt) {
            tmpContent = AppUtils.aesEncrypt(writeContent, AppUtils.byteArrayToHexString(tag.id))
        }

        return arrayOf(NdefRecord.createTextRecord(Locale.getDefault().language, tmpContent))
    }


}